/*
 * @Description: 工具集
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-10-12
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-24
 */

/**
 * 克隆
 */
export function cloneFnJSON<T>(source: T): T {
  return JSON.parse(JSON.stringify(source))
}

/**
 * 姓名加密
 * @param name 姓名
 * @returns
 */
export const secretName = (name: string) => {
  if (!name) return '***'
  return name.substring(0, 1) + '*'.repeat(name.length - 1)
}

/**
 * 手机号加密
 * @param phone 手机号
 * @returns
 */
export const secretPhone = (phone: string) => {
  if (!phone) return '***'
  return phone.substring(0, 3) + '****' + phone.substring(7, 11)
}

/**
 * 将数组的第一个元素移至末尾（改变原数组）
 * @param arr 原数组
 * @returns
 */
export const moveFirstToLast = <T>(arr: T[]) => {
  const firstElement = arr.shift() as T
  arr.push(firstElement)
  return arr
}

/**
 * 节流函数
 * @param callback 回调函数
 * @returns
 */
export const limit = (callback: Function) => {
  let next = true
  return (...params: any) => {
    if (next) {
      next = false
      callback(() => (next = true), ...params)
    }
  }
}

/**
 * 睡眠函数
 * @param time 暂停时长：单位ms
 */
export const sleep = async (time: number) => {
  await new Promise<void>((resolve) => {
    setTimeout(() => resolve(), time)
  })
}

/**
 * 删除数组元素
 * @param arr 数组
 * @param item 元素
 * @returns
 */
export const deleteArrayItem = <T>(arr: T[], item: T): T[] => {
  const newSet = new Set(arr)
  newSet.delete(item)
  return [...newSet]
}

/**
 * 重载当前页面
 */
export const reloadCurrPage = () => {
  const pages = getCurrentPages()
  const currPage = pages[pages.length - 1]
  const { route, options } = currPage
  uni.redirectTo({ url: `/${route}${convertParamToString(options)}` })
}

/**
 * 转换页面参数为字符串
 */
export const convertParamToString = (param: Object) => {
  let result = ''
  Object.entries(param).forEach((item, i) => {
    result += `${i === 0 ? '?' : '&'}${item[0]}=${item[1]}`
  })
  return result
}

/**
 * 删除Html标签，保留text
 */
export const delHtmlTag = (htmlString: string) => {
  const dd = htmlString.replace(/<\/?.+?>/g, '')
  const dds = dd.replace(/ /g, '') //dds为得到后的内容
  return dds
}

/**
 * 下载文件，打开文档
 */
export const openDocument = (url: string) => {
  const fileType: string = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
  if (fileType !== 'pdf') {
    uni.showToast({ title: '当前文件不支持预览', icon: 'none', duration: 4000 })
    return
  }
  wx.showLoading({
    title: '正在下载文件',
  })
  wx.downloadFile({
    url,
    success: function (res) {
      const filePath = res.tempFilePath
      wx.openDocument({
        filePath: filePath,
        fileType: 'pdf',
        fail: function (err) {
          uni.showToast({ title: err.errMsg, icon: 'none', duration: 4000 })
        },
      })
    },
    fail: function (err) {
      uni.showToast({ title: err.errMsg, icon: 'none', duration: 4000 })
    },
    complete() {
      wx.hideLoading()
    },
  })
}

/**
 * 判断是否图片类型
 */
export const isImage = (url: string) => {
  const fileType: string = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
  return ['bmp', 'jpg', 'jpeg', 'png', 'webp', 'apng', 'gif'].includes(fileType)
}
